package com.pignest.hotel.beans;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import com.pignest.hotel.annotation.Bean;
import com.pignest.hotel.beans.global.BaseBean;
import com.pignest.hotel.system.Permission;

@Bean("角色")
public class Role extends BaseBean {
	private static final long serialVersionUID = -5756606938399409833L;
	
	private String name;
	private String description;
	private Set<ACL> acls;
	
	public Role() {
	}
	
	public Role(String name, Permission... permissions) {
		this.name = name;
		acls = new HashSet<ACL>();
		for (int i = 0; i < permissions.length; i++) {
			acls.add(new ACL(this, permissions[i].name()));
		}
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public Collection<ACL> getAcls() {
		return acls;
	}
	public void setAcls(Set<ACL> acls) {
		this.acls = acls;
	}
	
	////////////////////////////////
	
	public void setPermissions(List<String> ps) {
		if (ps == null || ps.isEmpty()) {
			this.acls = null;
			return;
		}
		if (acls == null || acls.isEmpty()) {
			acls = new HashSet<ACL>();
			for (int i = 0, j=ps.size(); i < j; i++) {
				acls.add(new ACL(this, ps.get(i)));
			}
		} else {
			HashMap<String, ACL> map = new HashMap<String, ACL>();
			if (acls == null) {
				acls = new HashSet<ACL>();
			} else {
				for (ACL acl : acls) {
					map.put(acl.getPermission(), acl);
				}
			}
			ArrayList<ACL> newAcls = new ArrayList<ACL>();
			for (int i = 0, j=ps.size(); i < j; i++) {
				ACL acl = map.get(ps.get(i));
				if (acl == null)
					acl = new ACL(this, ps.get(i));
				newAcls.add(acl);
			}
			acls.clear();
			acls.addAll(newAcls);
		}
	}
	
	public boolean hasPermission(String p) {
		if (StringUtils.isEmpty(p))
			return true;
		if (acls == null || acls.isEmpty())
			return false;
		for (ACL acl : acls) {
			if (p.equals(acl.getPermission()))
				return true;
		}
		return false;
	}
	
	@Override
	public String toSimpleString() {
		return name;
	}
}
